package zero.mybatisplus.dynamictable.demo.controller;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.elasticsearch.action.ActionListener;
import org.elasticsearch.action.admin.indices.delete.DeleteIndexRequest;
import org.elasticsearch.action.support.master.AcknowledgedResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.indices.GetIndexRequest;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.reindex.BulkByScrollResponse;
import org.elasticsearch.index.reindex.DeleteByQueryRequest;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import zero.mybatisplus.dynamictable.demo.entity.ZeroEntity;
import zero.mybatisplus.dynamictable.demo.mapper.ZeroMapper;
import zero.mybatisplus.dynamictable.demo.service.IZeroService;
import zero.mybatisplus.dynamictable.emnus.TypeEnums;
import zero.mybatisplus.dynamictable.param.DynamicTableParam;

import javax.annotation.Resource;
import java.io.IOException;
import java.sql.Timestamp;
import java.util.Date;

@RestController
@Api(tags = "测试")
@RequestMapping("/zero")
public class ZeroController {
    @Resource
    private IZeroService zeroService;
    @Resource
    private ZeroMapper zeroMapper;

    @GetMapping("/save")
    @ApiOperation(value = "新增", notes = "新增")
    @Transactional
    public void save() {
        zeroMapper.getInfo();
//        ZeroEntity zeroEntity = new ZeroEntity();
//        zeroEntity.setId("11");
//        zeroEntity.setName("zero-1");
//        zeroEntity.setDate(new Timestamp(System.currentTimeMillis()));
//        zeroService.save(zeroEntity);
    }

    @GetMapping("/update")
    @ApiOperation(value = "修改", notes = "修改")
    @Transactional
    public void update() {
        ZeroEntity zeroEntity = new ZeroEntity();
        zeroEntity.setId("11");
        zeroEntity.setName("zero-1");
        zeroEntity.setDate(new Timestamp(System.currentTimeMillis()));
        zeroService.updateById(zeroEntity);
    }

    @GetMapping("/del")
    @ApiOperation(value = "删除", notes = "删除")
    @Transactional
    public void del() {
        DynamicTableParam zero = DynamicTableParam.initDateValue("t_zero", TypeEnums.YEAR_MONTH_TABLE, "20201212");
        zeroService.delById("11",zero);
    }

    @GetMapping("/get")
    @ApiOperation(value = "获取一条", notes = "获取一条")
    public void get() {
        DynamicTableParam zero = DynamicTableParam.initDateValue("t_zero", TypeEnums.YEAR_MONTH_TABLE, "20201212");
        zeroService.getById("11",zero);
    }


//    private static final String INDEX = "zero";
//    private static final String INDEX_TYPE = "doc";
//    @Resource
//    private RestHighLevelClient restClient;

//    @GetMapping("/insert")
//    @ApiOperation(value = "创建索引和插入数据", notes = "")
//    public void insert() throws IOException {
//
//        while (true){
//            ElasticsearchPo esPo = new ElasticsearchPo();
//            Zero zero1 = new Zero();
//            zero1.setAge(1);
//            zero1.setName("名称");
//            esPo.setZero(zero1);
//            List<Zero> list = new ArrayList<>();
//            list.add(zero1);
//            esPo.setZeroList(list);
//            Map<String, String> map = new HashMap<>();
//            map.put("zero", "zero");
//            map.put("zero1", "zero");
//            map.put("zero2", "zero");
//            esPo.setOther(map);
//
//            //索引请求对象
//            IndexRequest indexRequest = new IndexRequest(INDEX, INDEX_TYPE);
//            //指定索引文档内容
//            indexRequest.source(JSONUtil.toJsonStr(esPo), XContentType.JSON);
//
//            restClient.index(indexRequest, RequestOptions.DEFAULT);
//        }
//    }
//
//
//    @PostMapping("/page")
//    @ApiOperation(value = "分页信息", notes = "")
//    public Object page(@RequestBody EsQuery query) throws IOException {
//        int current = query.getCurrent();
//        int size = query.getSize();
//        //设置要查询的索引 和 type
//        SearchRequest searchRequest = new SearchRequest(INDEX);
//        searchRequest.types(INDEX_TYPE);
//        SearchSourceBuilder searchBuilder = new SearchSourceBuilder();
//
//        //分页查询，设置起始下标，从0开始
//        searchBuilder.from((current - 1) * size);
//        //每页显示个数
//        searchBuilder.size(size);
//        BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
////        boolQueryBuilder.must(QueryBuilders.rangeQuery("time").gte(1614916134916L).lte(1614916134916L));
//        //普通模糊匹配
//        boolQueryBuilder.must(QueryBuilders.wildcardQuery("commonEnum", "wsh"));
//        boolQueryBuilder.must(QueryBuilders.matchQuery("zero.name", "名称"));
//        searchBuilder.query(boolQueryBuilder);
//
//        //时间倒序
//        searchBuilder.sort(new FieldSortBuilder("time").order(SortOrder.DESC));
//        //各种组合条件和排序
//        searchRequest.source(searchBuilder);
//        //查询结果对象
//        SearchResponse search = restClient.search(searchRequest, RequestOptions.DEFAULT);
//        SearchHits hits = search.getHits();
//        long totalHits = hits.getTotalHits();
//        //分页对象
//        PageResult pageResult = new PageResult();
//        pageResult.setCurrent(current);
//        pageResult.setSize(size);
//        pageResult.setPages((totalHits + size - 1) / size);
//        pageResult.setTotal(totalHits);
//        pageResult.setRecords(Arrays.stream(hits.getHits()).map(SearchHit::getSourceAsMap).collect(Collectors.toList()));
//        return pageResult;
//    }

//
//    /**
//     * 批量删除文档
//     *
//     * @throws IOException
//     */
//    @PostMapping("/del")
//    @ApiOperation(value = "删除", notes = "")
//    public void deleteByQueryRequest() throws IOException {
//        DeleteByQueryRequest request = new DeleteByQueryRequest(INDEX);
//        request.setDocTypes(INDEX_TYPE);
//        request.setQuery(QueryBuilders.rangeQuery("time").gte(1614839520000L).lte(1615028343000L));
//        restClient.deleteByQueryAsync(request, RequestOptions.DEFAULT, new ActionListener<BulkByScrollResponse>() {
//            @Override
//            public void onResponse(BulkByScrollResponse response) {
//                System.out.println("正常");
//            }
//
//            @Override
//            public void onFailure(Exception e) {
//                System.out.println("异常");
//            }
//        });
//    }
//
//    /**
//     * 批量删除文档
//     *
//     * @throws IOException
//     */
//    @PostMapping("/delIndex")
//    @ApiOperation(value = "删除索引", notes = "")
//    public void delIndex() throws IOException {
//        DeleteIndexRequest request = new DeleteIndexRequest(INDEX);
//        AcknowledgedResponse delete = restClient.indices().delete(request, RequestOptions.DEFAULT);
//        boolean acknowledged = delete.isAcknowledged();
//        if (acknowledged) {
//            System.out.println("删除成功！");
//        }
//    }
//
//    /**
//     * 批量删除文档
//     *
//     * @throws IOException
//     */
//    @PostMapping("/exist")
//    @ApiOperation(value = "是否存在索引", notes = "")
//    public void exist() throws IOException {
//        GetIndexRequest request = new GetIndexRequest(INDEX);
//        boolean exists = restClient.indices().exists(request, RequestOptions.DEFAULT);
//
//    }
}
